#include "server.h"

#include <QtGui>

ServerInfo::ServerInfo() : port(21), proxyPort(21)
{
}

ServerInfo::ServerInfo(const ServerInfo &info) :
    host(info.host), user(info.user), pass(info.pass), dir(info.dir),
    proxyHost(info.proxyHost),
    port(info.port), proxyPort(info.proxyPort)
{
}

Server::Server(QObject *parent) : QObject(parent), myConnId(-1)
{
  myHttp = new QHttp(this);

  //connect(myHttp, SIGNAL(requestFinished(int,bool)), this, SLOT(commandFinished(int,bool)));
  connect(myHttp, SIGNAL(done(bool)), this, SLOT(done(bool)));
  connect(myHttp, SIGNAL(stateChanged(int)), this, SIGNAL(stateChanged(int)));
}

void Server::setInfo(const ServerInfo &info)
{
  myInfo = info;
  myHttp->setHost(myInfo.host, QHttp::ConnectionModeHttp, myInfo.port);
  myHttp->setProxy(myInfo.proxyHost, myInfo.proxyPort);
}


void Server::done(bool err)
{
  myCommandFinished = true;
  myCommandError = err;
  qDebug() << myHttp->errorString();
}

bool Server::connectServer()
{
  myCommandError = myCommandFinished = false;
  return true;
}

int Server::getFile(const QString &serverPath, const QString &localPath, const QString &name)
{
  QFile file(localPath + "/" + name);
  if (!file.open(QIODevice::WriteOnly))
    return 0;

  // binary getting
  myCommandError = myCommandFinished = false;
  myConnId = myHttp->get(QUrl::toPercentEncoding(serverPath + "/" + name, "!$&'()*+,;=:@/"), &file);

  // wait for signal
  while (!myCommandFinished)
  {
    QApplication::processEvents();
  }

  file.flush();
  file.close();

  if (myCommandError)
    return 0;

  return file.size();
}
